package attribute

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateAttributeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateAttributeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAttributeLogic {
	return &CreateAttributeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateAttributeLogic) CreateAttribute(in *product.AttributeInfo) (*product.BaseIDResp, error) {
	// logx.Infof("CreateTerm : %+v ", in)

	if in.Name == nil || len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("attribute.nameRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	attribute := &model.Attribute{
		Name: strings.TrimSpace(*in.Name),
	}
	if in.Slug != nil { // 允许为空，不管长度
		attribute.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.TermId != nil {
		attribute.TermID = *in.TermId
	}
	if in.Taxonomy != nil {
		attribute.Taxonomy = *in.Taxonomy
	}
	if in.IsVariation != nil {
		attribute.IsVariationAttribute = uint8(*in.IsVariation)
	}
	if in.HasMedia != nil {
		attribute.HasImage = uint8(*in.HasMedia)
	}
	if in.Sort != nil {
		attribute.Sort = uint16(*in.Sort)
	} else {
		attribute.Sort = uint16(9999)
	}
	if in.Status != nil {
		attribute.Status = uint8(*in.Status)
	} else {
		attribute.Status = uint8(globalkey.StatusEnabled)
	}
	now := time.Now()
	attribute.CreatedAt = now
	attribute.UpdatedAt = now

	err = l.svcCtx.Attribute.Insert(l.ctx, tx, attribute, nil)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &product.BaseIDResp{
		Id:  attribute.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
